﻿using System;
using System.Collections.Generic;
using System.Linq;
using oModbus.Utility;

namespace oModbus.Message
{
    public class WriteSingleCoilResponse : AbstractModbusMessage
    {
        public WriteSingleCoilResponse(byte slaveAddress, ushort coilAddress, ushort value) : base(slaveAddress, FunctionCode.WriteSingleCoil)
        {
            CoilAddress = coilAddress;
            Value = value;
        }
        public WriteSingleCoilResponse(byte[] messageBytes) : base(messageBytes)
        {
        }

        /// <summary>
        /// 线圈地址
        /// </summary>
        public ushort CoilAddress { get; set; }
        /// <summary>
        /// 值
        /// </summary>
        public ushort Value { get; set; }

        protected override void Packing()
        {
            base.Packing();
            MessageData.AddRange(CoilAddress.GetBytes());//开始地址
            MessageData.AddRange(Value.GetBytes());//长度  
            Crc = MessageData.ToArray().CalculateCrc();

        }

        public override bool Analysis(byte[] messageBytes)
        {
            if (messageBytes.Length >= 8)
            {
                MessageData = messageBytes.ToList();
                SlaveAddress = messageBytes[0];
                FunctionCode = (FunctionCode)Convert.ToInt32(messageBytes[1]);
                CoilAddress = ConvertExtend.GetUint16(messageBytes[2], messageBytes[3]);
                Value = ConvertExtend.GetUint16(messageBytes[4], messageBytes[5]);

                Crc = new List<byte>() {
                    messageBytes[messageBytes.Length - 2],
                    messageBytes[messageBytes.Length - 1]
                }.ToArray();
                return true;
            }
            return false;
        }
    }
}
